<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    :destroy-on-close="true"
    title="添加部件"
    ok-text="保存"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { schemas } from './addWidgetsModal.data';
  import { ref } from 'vue';
  import { modalFormStyleSetting } from '/@/settings/thingsBoardDesign';
  import { getBundleWidgetTypeInfos } from '/@/api/thingsborad/resources/widgets/widgets';
  const emit = defineEmits(['success']);
  const recordId = ref<string>();
  const [registerModal, { closeModal, setModalProps }] = useModalInner(async ({ id }) => {
    setModalProps({ confirmLoading: true });
    recordId.value = id;
    const { data } = await getBundleWidgetTypeInfos({
      pageSize: 1024,
      page: 0,
      widgetsBundleId: id,
      fullSearch: false,
      deprecatedFilter: 'ALL',
    });
    if (data.length > 0) {
      let widgetIds: string[] = [];
      data.forEach((item: Recordable) => {
        widgetIds.push(item.id.id);
      });

      setFieldsValue({ widgetIds });
    }
    setModalProps({ confirmLoading: false });
  });
  const [registerForm, { validate, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas,
    ...modalFormStyleSetting,
    showActionButtonGroup: false,
  });
  const handleSubmit = async () => {
    const values = await validate();
    emit('success', {
      values: { widgetIds: values, packageId: recordId.value },
      key: 'addWidgets',
    });
    closeModal();
  };
</script>
